#!/usr/bin/env python
# coding: utf-8
import web
from config import settings,util
from config.settings import session
from datetime import datetime
import sys,os,shutil
import ConfigParser
import hashlib
import authbase

db = settings.db
render_login = web.template.render('templates/')
render = settings.render
tb="users"
class Index(authbase.AuthBase):
    def GET(self):
        users = db.select(tb)
        return render.users.index(users=users)

def get_by_id(id):
    try:
        return db.select(tb, where = 'id=$id', vars = locals())[0]
    except IndexError:
        return None


class New:
    def GET(self):
        new_user=""
        return render.users.new(new_user="")

class Create:
    def POST(self):
        i = web.input()
        login_name = i.get('login_name', None)
        if not login_name:
            return render.error('登录名称不能为空', None)
        user_name = i.get('user_name', None)
        if not user_name:
            return render.error('姓名不能为空', None)
        password = i.get('password', None)
        if not password:
            return render.error('密码不能为空', None)
        is_admin_input = i.get('is_admin', None)
        if is_admin_input=='is_admin':
            is_admin=True
        else:
            is_admin=False

        md5_password=hashlib.md5(password).hexdigest()
        db.insert(tb,login_name=login_name, user_name=user_name,password=md5_password,is_admin=is_admin)
        raise web.seeother('/users')


class Edit(authbase.AuthBase):
    def GET(self, id):
        user = get_by_id(int(id))
        if not user:
            return render.error('没找到这条记录', None)
        return render.users.edit(new_user=user)

    def POST(self, id):
        user = get_by_id(int(id))
        if not user:
            return render.error('没找到这条记录', None)
        i = web.input()
        login_name = i.get('login_name', None)
        if not login_name:
            return render.error('登录名称不能为空', None)
        user_name = i.get('user_name', None)
        if not user_name:
            return render.error('姓名不能为空', None)
        password = i.get('password', None)
        if not password:
            return render.error('密码不能为空', None)
        is_admin_input = i.get('is_admin', None)
        if is_admin_input=='is_admin':
            is_admin=True
        else:
            is_admin=False
        md5_password=hashlib.md5(password).hexdigest()

        db.update(tb, login_name=login_name, user_name=user_name,password=md5_password,is_admin=is_admin, where='id=$id', vars=locals())
        return render.error('编辑成功！', '/users')

class Delete(authbase.AuthBase):
    def GET(self, id):
        user = get_by_id(int(id))
        if not user:
            return render.error('没找到这条记录', None)
        db.delete(tb, where='id=$id', vars=locals())
        return render.error('删除成功！', '/users')

